package com.google.code.irouter.batch.api;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.code.irouter.model.Human;
import com.google.code.irouter.utils.ModelUtil;

public abstract class Bot implements Serializable {

	private static final long serialVersionUID = -8950743107445914801L;

	protected abstract List<Human> getList(String userId);

	protected abstract List<Human> getList();
	
	public static boolean STOP = false;

	public void execute() {
		if(STOP) 
			return;
		List<Human> list = getList();
		regeist(list);
	}

	public void execute(String userId) {
		if(STOP) 
			return;
		List<Human> list = getList(userId);
		regeist(list);
	}

	private void regeist(List<Human> list) {
		Human last = null;
		for (Human people : list) {
			Map<String, Object> query = new HashMap<String, Object>();
			query.put("id", people.getId());
			if(ModelUtil.select(Human.class, query).size() == 0) {			
				ModelUtil.save(people);
				last = people;
			}			
		}		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		com.google.appengine.api.taskqueue.Queue queue = QueueFactory
				.getQueue("catch");
		try {
			String userId = "";
			if(last != null)
				userId = last.getId();
			Transaction txn = ds.beginTransaction();
			queue.add(TaskOptions.Builder.withUrl("/cron/bot")
					.countdownMillis(1000 * 30)
					.method(TaskOptions.Method.GET)
					.param("userId", userId));
			txn.commit();

		} catch (DatastoreFailureException exception) {
			// TODO
		}
	}

}
